﻿using BZ.Logger;
using HZH_Controls;
using NDK.DB;
using NDK.Module.DAL;
using NDK.Module.Model;
using NDK.Module.StationLogic;
using NDK.Motion.StationLogic;
using NDK.Motion.Sys;
using NDK.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using static NDK.Module.Model.Common;

namespace NDK.Module.BLL
{
    public delegate void delegateUpdateUI(MeasureProduct battery);
    public delegate void delegateUpdateNGUI(MeasureProduct battery);
    public delegate void delegateShowMsgBox();

    class ProcessData
    {

        static object obj = new object();
        public static event delegateUpdateUI UpdateUIEvent;
        public static event delegateUpdateNGUI UpdateNGUIEvent;

        public static int SortMeasureSize(DataItem x, DataItem y)
        {
            if (x.ID > y.ID)
                return 1;
            if (x.ID < y.ID)
                return -1;
            return 0;
        }

        /// <summary>
        /// 结果判断进行分料
        /// </summary>
        /// <param name="measureProduct"></param>
        /// <returns></returns>
        public static JUDGEMENT_RESULT PrcessData(MeasureProduct measureProduct, bool IsLineSaveImage = true)
        {
            lock (obj)
            {
                JUDGEMENT_RESULT ret = JUDGEMENT_RESULT.EMPTY;
                if (StationManager.MachineProductionMode == RunningModeEnum.EmptyMode) return ret;
                ret = Jugement.JugeMeasureData(ref measureProduct);
                
                measureProduct.Result = ret;
                DataItem FAI_RANDOM_SAMPLE = new DataItem();
                FAI_RANDOM_SAMPLE.Name = "FAI_RANDOM_SAMPLE";
                measureProduct.MeasureData.Add(FAI_RANDOM_SAMPLE);
                FAI_RANDOM_SAMPLE.Value = 0;

                DataTable dataTable = new DataTable();
                if (!measureProduct.SN.Contains("NDK"))
                {
                    dataTable = MySQLDBHelper.QueryDataBySN1(measureProduct.SN);
                    if (dataTable != null && dataTable.Rows.Count == 0) //没有复测过
                    {
                        if (ret != JUDGEMENT_RESULT.OK)
                            MySQLDBHelper.InsertNGRecordData(measureProduct.SN, 0, 1);
                        else
                            MySQLDBHelper.InsertNGRecordData(measureProduct.SN, 1, 0);
                    }
                    else
                    {
                        string[] strings = MySQLDBHelper.QueryNGTimesData1(measureProduct.SN).Split(';'); //查询一下复测次数
                        if (ret != JUDGEMENT_RESULT.OK)
                            MySQLDBHelper.UpdateNGRecordData(measureProduct.SN, strings[0].ToInt(), strings[1].ToInt() + 1);
                        else
                            MySQLDBHelper.UpdateNGRecordData(measureProduct.SN, strings[0].ToInt() + 1, strings[1].ToInt());
                    }
                }
                #region OK品抽检功能  RANDOM_SAMPLE尺寸标记
                bool isContainNGitem = false;//是否含有配置的NG项   
                if (ret == JUDGEMENT_RESULT.OK)
                {
                    Common.FAIListError = new List<string>();
                    measureProduct.OK_NG = "OK";
                    FAI_RANDOM_SAMPLE.Value = 0;//OK产品标记的值
                                                //抽样
                    if ((Common.r_Sample.NextDouble() * 100 < Common.samplePersent) && Common.isSample == true)
                    {
                        //if (Directory.Exists("D:\\Data")) Directory.CreateDirectory("D:\\Data");
                        //FileUtils.AppendText(@"D:\Data\Sample.csv", measureProduct.SN + "__" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "," + "\r\n");
                        try
                        {
                            ret = JUDGEMENT_RESULT.ORT;//返回ORT
                            measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value = 1;
                            Common.curSampleCount++;
                            if (Common.curSampleCount >= Common.sampleCount)//抽样数量足够关闭抽样功能
                            {
                                Common.isSample = false;
                                Common.samplePersent = 0;
                                Common.curSampleCount = 0;
                                Common.sampleCount = 0;
                            }
                        }
                        catch
                        { }
                    }
                }
                else
                {
                    if (ret == JUDGEMENT_RESULT.NA)
                        measureProduct.OK_NG = "NA";
                    else
                        measureProduct.OK_NG = "NG";
                    if (ret == JUDGEMENT_RESULT.NG)//在上下限公差的5%以内    标记3
                    {
                        measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value = 3;
                    }
                    else if (ret == JUDGEMENT_RESULT.EXCEPTION)//超出上下限公差的5%    标记为5
                    {
                        measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value = 5;
                    }
                    else if (ret == JUDGEMENT_RESULT.NA)//NA    2
                    {
                        measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value = 2;
                    }
                }

                if (Sample_4 == true)//手动标记为4   强制可以复测
                {
                    measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value = 4;
                }
                #endregion

                #region 上传MES系统
                if (!屏蔽Mes上传 && IsLineSaveImage)//数据上传至MES
                {
                    if (Line == "左")
                    {
                        string datastr = "";
                        foreach (var item in measureProduct.MeasureData)
                            datastr += item.Value + "@" + item.Name + ";";
                        StationTCP.SendStr_ClientComputer($"Data,{measureProduct.SN},{measureProduct.Position},{ret},{datastr}");
                    }

                    //if (measureProduct.StrInCheck != "OK")
                    //{
                    //    measureProduct.NG_FAI = "Upload Fail||" + measureProduct.NG_FAI;
                    //    ret = JUDGEMENT_RESULT.NG;
                    //}
                    //else
                    //{
                    //    if (Line == "右")
                    //    {
                    //        StationTCP.DicStrOutCheckStatus_L.Add(measureProduct.SN, "");
                    //        string strmess = measureProduct.SN;
                    //        strmess += "," + measureProduct.Position;
                    //        strmess += "," + "OK";
                    //        string itemStr = string.Empty;
                    //        foreach (var item in measureProduct.MeasureData)
                    //            itemStr += item.Value + "@" + item.Name + "@" + "OK" + ";";
                    //        strmess += "," + itemStr;
                    //        StationTCP.SendMesSever($"OutCheckL,{strmess}");
                    //        DateTime dateTime = DateTime.Now;
                    //        while (StationTCP.DicStrOutCheckStatus_L[measureProduct.SN] == "")
                    //        {
                    //            if ((DateTime.Now - dateTime).TotalSeconds > 2)
                    //            {
                    //                if (MessageBox.Show("出站信号无回馈,请检查Mes是否掉线", "左线出站", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    //                {
                    //                    dateTime = DateTime.Now;
                    //                    StationTCP.SendMesSever($"OutCheckL,{strmess}");
                    //                }
                    //                else
                    //                {
                    //                    StationTCP.DicStrOutCheckStatus_L[measureProduct.SN] = "NG";
                    //                    break;
                    //                }
                    //            }
                    //        }
                    //        if (StationTCP.DicStrOutCheckStatus_L[measureProduct.SN] != "OK")
                    //        {
                    //            measureProduct.NG_FAI = "Upload Fail||" + measureProduct.NG_FAI;
                    //            ret = JUDGEMENT_RESULT.NG;
                    //            AppendUiLog.Log($"左线:该产品{measureProduct.SN} 出站失败", LogType.Error);
                    //        }
                    //        StationTCP.DicStrOutCheckStatus_L.Remove(measureProduct.SN);
                    //    }
                    //    else
                    //    {
                    //        StationTCP.DicStrOutCheckStatus_R.Add(measureProduct.SN, "");
                    //        string strmess = measureProduct.SN;
                    //        strmess += "," + measureProduct.Position;
                    //        strmess += "," + "OK";
                    //        string itemStr = string.Empty;
                    //        foreach (var item in measureProduct.MeasureData)
                    //            itemStr += item.Value + "@" + item.Name + "@" + "OK" + ";";
                    //        strmess += "," + itemStr;
                    //        StationTCP.SendMesSever($"OutCheckR,{strmess}");
                    //        DateTime dateTime = DateTime.Now;
                    //        while (StationTCP.DicStrOutCheckStatus_R[measureProduct.SN] == "")
                    //        {
                    //            if ((DateTime.Now - dateTime).TotalSeconds > 2)
                    //            {
                    //                if (MessageBox.Show("出站信号无回馈,请检查Mes是否掉线", "左线出站", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
                    //                {
                    //                    dateTime = DateTime.Now;
                    //                    StationTCP.SendMesSever($"OutCheckR,{strmess}");
                    //                }
                    //                else
                    //                {
                    //                    StationTCP.DicStrOutCheckStatus_R[measureProduct.SN] = "NG";
                    //                    break;
                    //                }
                    //            }
                    //        }
                    //        if (StationTCP.DicStrOutCheckStatus_R[measureProduct.SN] != "OK")
                    //        {
                    //            measureProduct.NG_FAI = "Upload Fail||" + measureProduct.NG_FAI;
                    //            ret = JUDGEMENT_RESULT.NG;
                    //            AppendUiLog.Log($"右线:该产品{measureProduct.SN} 出站失败", LogType.Error);
                    //        }
                    //        StationTCP.DicStrOutCheckStatus_R.Remove(measureProduct.SN);
                    //    }
                    //}
                }
                #endregion

                #region 刷新数据界面  保存数据csv  
                if (ret == JUDGEMENT_RESULT.OK)
                {
                    TotalCount++;
                    //刷新FormHome窗体
                    UpdateUIEvent.BeginInvoke(measureProduct, null, null);
                }
                else
                {
                    if (ret == JUDGEMENT_RESULT.NA)
                        NACount++;
                    else
                        NGCount++;

                    TotalCount++;
                    //刷新FomHome显示NG的DataGrad窗体
                    UpdateNGUIEvent.BeginInvoke(measureProduct, null, null);
                }
                #endregion

                //保存数据至数据库
                PublicMethod.SaveDataCSV(measureProduct, true, IsLineSaveImage);

                //if (measureProduct.MeasureData.SingleOrDefault(name => name.Name == PPGName_L).JugeResult == JUDGEMENT_RESULT.NG.ToString()
                //    || measureProduct.MeasureData.SingleOrDefault(name => name.Name == PPGName_R).JugeResult == JUDGEMENT_RESULT.NG.ToString())
                //{
                //    Common.PPGCountNG++;
                //    if (Common.PPGCountNG >= Common.PPG异物NG片数)
                //    {
                //        Common.PPGCountNG = 0;
                //        MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                //        MessageBox.Show("PPG 异物预警,请检查机台");
                //    }
                //}
                if (Common.isForceOK) ret = JUDGEMENT_RESULT.OK;
                if (Common.isForceNG) ret = JUDGEMENT_RESULT.NG;
                if (Common.isForceORT) ret = JUDGEMENT_RESULT.ORT;
                return ret;
            }
        }

        private static readonly object _lock = new object();

        private static string UploadMacMini(MeasureProduct measureProduct)
        {
            string str_SendToApple = string.Empty;
            try
            {

                string appleQrSN = measureProduct.SN.Split('+')[0];
                str_SendToApple += "_{" + "\n";
                str_SendToApple += appleQrSN + "@start" + "\n";

                //尺寸提取及整合
                MeasureSizeServices measureSizeServices = new MeasureSizeServices();
                List<MeasureSize> measureSizeList = measureSizeServices.GetAllByProjectNameAndTurnNum(CurProType, Convert.ToInt32(measureProduct.Position));
                foreach (DataItem cameraData in measureProduct.MeasureData)//遍历所有尺寸var cameraData in battery.MeasureData
                {
                    MeasureSize measureSizeUploadApple = measureSizeList.SingleOrDefault(size => size.SizeName == cameraData.Name);

                    if (measureSizeUploadApple == null)
                    {
                        continue;//如果该工程下没有这个尺寸，放弃上传
                    }
                    if (cameraData.Name != "FAI_RANDOM_SAMPLE" && !measureSizeUploadApple.IsShow)
                    {
                        string appleValue = cameraData.Value.ToString("0.0000");
                        string Uppervalue = (measureSizeUploadApple.NormValue + measureSizeUploadApple.UpperDeviation).ToString();
                        string LowerValue = (measureSizeUploadApple.NormValue - measureSizeUploadApple.LowerDeviation).ToString();

                        if (!measureSizeUploadApple.IsJudging)
                        {
                            if (Math.Abs(cameraData.Value) > 500)
                            {
                                str_SendToApple += appleQrSN
                                                            + "@pdata"
                                                            + "@" + cameraData.Name
                                                            + "@" + "999"
                                                            + "@" + LowerValue
                                                            + "@" + Uppervalue
                                                            + "@" + "mm" + "\n"; //+Environment.NewLine;
                            }
                            else
                            {
                                str_SendToApple += appleQrSN
                                                            + "@pdata"
                                                            + "@" + cameraData.Name
                                                            + "@" + appleValue
                                                            + "@" + LowerValue
                                                            + "@" + Uppervalue
                                                            + "@" + "mm" + "\n"; //+Environment.NewLine;
                            }
                        }
                        else
                        {
                            if (Common.isForceOK == true)//强制OK不需要再修改为99999
                            {
                                Uppervalue = "NA";
                                LowerValue = "NA";
                            }

                            if (cameraData.Value > 500 || cameraData.Value < -500)
                            {
                                str_SendToApple += appleQrSN
                                                            + "@pdata"
                                                            + "@" + cameraData.Name
                                                            + "@" + "999"
                                                            + "@" + LowerValue
                                                            + "@" + Uppervalue
                                                            + "@" + "mm" + "\n"; //+ Environment.NewLine;
                            }
                            else
                            {
                                str_SendToApple += appleQrSN
                                                            + "@pdata"
                                                            + "@" + cameraData.Name
                                                            + "@" + appleValue
                                                            + "@" + LowerValue
                                                            + "@" + Uppervalue
                                                            + "@" + "mm" + "\n"; //+ Environment.NewLine;
                            }
                        }
                    }
                }

                str_SendToApple += appleQrSN
                                            + "@pdata"
                                            + "@" + "FAI_RANDOM_SAMPLE"
                                            + "@" + measureProduct.MeasureData.SingleOrDefault(size => size.Name == "FAI_RANDOM_SAMPLE").Value.ToString()
                                            + "@" + "NA"
                                            + "@" + "NA"
                                            + "@" + "mm" + "\n"; //Environment.NewLine;


                //结束语
                str_SendToApple += appleQrSN + "@" + "submit@NDKMeasurement_" + Common.currentVersion + "\n"; // Environment.NewLine;

                //加入结束符
                str_SendToApple += "}" + "\n"; //Environment.NewLine;
                appleQrSN = "";
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log("上传数据整合异常!" + ex.ToString(), LogType.Error);
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                if (MessageBox.Show("上传数据整合异常!" + ex.ToString()) == DialogResult.OK)
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
                else
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
            }
            return str_SendToApple;

        }

        private static bool SendMacMini(string str, string Code, ref string strNG, string Line)
        {
            bool ret = true;
            int SendErrCount = 0;
        SendApple:
            //发送字符串
            try
            {
                Common.AsyncClient_MacMini.SendAsync(str);
                WriteLogToTxt(Line + ":" + str);

                //等待MacMini回复上传Ok信号
                Stopwatch sw = new Stopwatch();
                sw.Restart();
                while (true)
                {
                    if (Common.AsyncRcvMsgFromMacMini == "MacMiniOk")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log(Line + ":上传数据到MacMini成功", LogType.Info);
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniNg")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log(Line + ":上传数据到MacMini失败!", LogType.Error);

                        ret = false;
                        strNG = "UploadAppleNG" + "||" + strNG;
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniErr")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log(Line + ":MacMini未过站，排出！", LogType.Error);

                        ret = false;
                        strNG = "UploadApple AE-1_Fail" + "||" + strNG;
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniBad")
                    {
                        Common.AsyncRcvMsgFromMacMini = "";
                        Common.AppendUiLog.Log(Line + ":上传数据到MacMini失败!", LogType.Error);

                        ret = false;
                        strNG = "UploadAppleBad" + "||" + strNG;
                        break;
                    }
                    else if (Common.AsyncRcvMsgFromMacMini == "MacMiniErrWithoutStart")
                    {
                        SendErrCount++;
                        Common.AsyncRcvMsgFromMacMini = "";

                        if (SendErrCount < 3)
                        {
                            //发送二维码信息
                            string send = string.Empty;
                            string appleQrSN = Code;

                            send += appleQrSN + "@start" + "\n";

                            Common.AsyncClient_MacMini.SendAsync(send);
                            WriteLogToTxt(send);

                            goto SendApple;
                        }
                        else
                        {
                            Common.AppendUiLog.Log(Line + ":MacMini上传异常，请检查接收端Log异常信息！", LogType.Error);

                            ret = false;
                            strNG = "UploadApple AE-1_Fail" + "||" + strNG;
                            break;
                        }
                    }
                    else
                    {
                        if (sw.ElapsedMilliseconds > 5000)
                        {
                            sw.Reset();
                            sw.Stop();

                            ret = false;
                            strNG = "UploadAppleTimeOut" + "||" + strNG;
                            Common.AppendUiLog.Log(Line + ":接收MacMini回传超时!", LogType.Error);
                            WriteLogToTxt(Line + ":接收MacMini回传超时!" + "\r\n");

                            MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                            if (MessageBox.Show(Line + ":接收MacMini回传超时! 请检查MacMini是否正常！") == DialogResult.OK)
                            {
                                MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                            }
                            else
                            {
                                MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                            }

                            break;
                        }
                    }

                    Thread.Sleep(10);
                }
            }
            catch (Exception ex)
            {
                Common.AppendUiLog.Log(Line + ":上传数据到MacMini异常!" + ex.ToString(), LogType.Error);
                WriteLogToTxt(Line + ":上传数据到MacMini异常!" + ex.ToString() + "\r\n");
                MachineStatusManager.CurrentMachineStatus = MachineStatus.Alarm;
                if (MessageBox.Show(Line + ":上传数据到MacMini异常!" + ex.ToString()) == DialogResult.OK)
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }
                else
                {
                    MachineStatusManager.CurrentMachineStatus = MachineStatusManager.LastMachineStatus;
                }

                ret = false;
                strNG = "UploadAppleAbnormal" + "||" + strNG;
            }
            return ret;
        }

        private static bool UploadMES(MeasureProduct measureProduct)
        {
            bool ret = true;
            try
            {
                List<string> paramFAIUploadMes = new List<string>();
                MeasureSizeServices measureSizeServices = new MeasureSizeServices();

                foreach (var cameraData in measureProduct.MeasureData)//遍历所有尺寸
                {
                    MeasureSize measureSizeUploadMes = measureSizeServices.GetModelByProjectNameAndSizeName(Common.ProjectName, cameraData.Name);
                    if (measureSizeUploadMes == null) continue;//如果该工程下没有这个尺寸，放弃上传
                    if (measureSizeUploadMes.IsShow == false) continue;//如果该尺寸号不需要显示，放弃上传
                                                                       //if (measureSizeUploadMes.IsJudging == false) continue;//如果该尺寸号不需要判定，放弃上传
                                                                       //if (measureSizeUploadMes.SizeName == "FAI-RANDOM-SAMPLE") continue;//如果该尺寸号是抽检标记，放弃上传
                    string mesValue = /*cameraData.Name + ":" +*/ cameraData.Value.ToString("0.000");
                    paramFAIUploadMes.Add(mesValue);
                }

                bool flagUploadResult = false;
                flagUploadResult = SMPMesUpload.SMPMesData_Collection_Auto(measureProduct, paramFAIUploadMes.ToArray());

                if (!flagUploadResult)//上传失败
                {
                    ret = false;
                    measureProduct.NG_FAI = "MesUpload Fail||" + measureProduct.NG_FAI;
                }
            }
            catch (Exception xxx)
            {
                Common.AppendUiLog.Log(measureProduct.SN + " :上传异常：" + xxx.ToString(), LogType.Error);
                measureProduct.NG_FAI = "MesUpload Fail||" + measureProduct.NG_FAI;
                ret = false;
            }
            return ret;
        }

        private static readonly object LogLock = new object();
        private static void WriteLogToTxt(string strLog)
        {
            lock (LogLock)
            {
                String System_Now_Time = null;
                String File_Create_Time = null;

                System_Now_Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff"); //"HH:mm:ss
                File_Create_Time = DateTime.Now.ToString("yyyyMMdd");
                string logDocument = File_Create_Time + ".txt";

                string str = Process.GetCurrentProcess().MainModule.FileName;
                string logFilePath = str.Substring(0, str.LastIndexOf("\\")) + "\\SendInfoLogMacMini";
                if (!Directory.Exists(logFilePath))
                {
                    Directory.CreateDirectory(logFilePath);
                }
                logFilePath = logFilePath + "//" + logDocument;
                FileStream fs = new FileStream(logFilePath, FileMode.Append);
                StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                sw.WriteLine(System_Now_Time + ":   " + strLog);
                sw.Flush();
                sw.Close();
                fs.Close();
            }
        }

        public static void SelectFAINGName(string str, ref List<string> strings)
        {
            List<bool> bools = new List<bool>();
            strings.Add(str.TrimEnd(';'));
            for (int i = 0; i < strings.Count; i++)
            {
                if (i > 0)
                {
                    bools.Add(false);
                    foreach (var name1 in strings[i - 1].Split(';'))
                    {
                        foreach (var name2 in strings[i].Split(';'))
                        {
                            if (name1 == name2) bools[i - 1] = true;
                        }
                    }
                }
            }
            int loacl = 1000;
            for (int i = 0; i < bools.Count; i++)
            {
                if (!bools[i]) loacl = i;
            }
            if (loacl != 1000)
            {
                for (int i = 0; i < loacl + 1; i++)
                {
                    strings.RemoveAt(0);
                }
            }
        }
    }

    public class MacMiniParam
    {
        public string str { get; set; }
        public string SN { get; set; }
        public string FAINg { get; set; }
    }
}

